package org.example.Servlet.TopicServlet;

import cn.hutool.core.lang.UUID;
import org.example.Dao.OptionDao;
import org.example.Dao.PersonDao;
import org.example.Dao.TopicDao;
import org.example.entity.Option;
import org.example.entity.Person;
import org.example.entity.Topic;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@WebServlet("/admin/topic/addTopic")
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB
        maxFileSize = 1024 * 1024 * 10,      // 10MB
        maxRequestSize = 1024 * 1024 * 50)    // 50MB
public class AddTopicServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private final String OPTION_IMAGE_SAVE_PATH = "F:\\progame code\\java\\jsp小组实验\\VoingSystem\\src\\web\\img\\option\\";
    private final String COVERIMAGE_IMAGE_SAVE_PATH = "F:\\progame code\\java\\jsp小组实验\\VoingSystem\\src\\web\\img\\coverimage\\";
    private final String WEB_PATH = "/";

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 设置请求和响应的字符编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        Topic topic = new Topic();
        List<Option> optionList = new ArrayList<>();
        PersonDao personDao = new PersonDao();
        HttpSession session = request.getSession();
        try {

            //从session中获取到管理员信息
            Person person = (Person) session.getAttribute("person");
            topic.setPid(person.getPid());
            topic.setAuthor(person.getUsername());
            // 1. 获取表单基本字段
            String title = request.getParameter("title");
            int status = Integer.parseInt(request.getParameter("status"));
            String desc = request.getParameter("desc");
            String beginDateStr = request.getParameter("beginDate");
            String endDateStr = request.getParameter("endDate");
            topic.setTitle(title);
            topic.setDesc(desc);
            // 2. 解析日期
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date beginDate = dateFormat.parse(beginDateStr);
            Date endDate = dateFormat.parse(endDateStr);
            topic.setBeginDate(beginDate);
            topic.setEndDate(endDate);
            topic.setStatus(status);
            String coverImagePath = null;
            // 4. 处理上传的封面图片
            Part filePart = request.getPart("coverImage");
            System.out.println("filePart ==>" + filePart);
            if (filePart != null && filePart.getSize() > 0) {
                String fileName = getFileName(filePart);
                coverImagePath = saveFile(filePart, fileName, true, request);
                System.out.println("upload file name(coverImage): " + fileName);
                System.out.println("coverImage file size: " + filePart.getSize() + " kb");
            }
            topic.setUrl(coverImagePath);

            String[] options = request.getParameterValues("option[]");
            if (options != null && options.length > 0) {
                System.out.println("option count: " + options.length);
                System.out.println("option content: " + Arrays.toString(options));
            } else {
                System.out.println("no option");
            }


            // 3. 获取上传的多文件
            Collection<Part> parts = request.getParts();
            List<Part> imageParts = new ArrayList<>();

            // 筛选出名称为"images[]"的文件
            for (Part part : parts) {
                // 匹配 optionImages[0], optionImages[1] 等参数
                if (part.getName().startsWith("images[")) {
                    imageParts.add(part);
                }
            }

            //保存option中的图片
            for (Part part : imageParts) {
                String fileName = getFileName(part);
                String optionUrl = saveFile(part, fileName, false, request);
                optionList.add(new Option(0, 0, optionUrl, ""));
            }
            System.out.println("imageParts size: " + imageParts.size());
            System.out.println("imageParts: " + imageParts);


            //为option 设置name
            for (int i = 0; i < options.length; i++) {
                optionList.get(i).setName(options[i]);
            }


            // 5. 调用TopicDao的addTopic方法添加主题
            TopicDao topicDao = new TopicDao();
            topic = topicDao.addTopic(topic);
            if (topic == null) {
                response.getWriter().println("处理请求时发生错误: 添加信息失败");
            }
            // 6. 调用OptionDao的addOption方法添加选项
            OptionDao optionDao = new OptionDao();
            int count = optionDao.addOptions(topic.getTid(), optionList);
            if (count > 0) {
                // 返回成功消息
                // 主备好普通用户信息
//                List<Person> personList = personDao.getNormalPersonList();
//                System.out.println("personList ==> " + personList.toString());
//                session.setAttribute("personList", personList);
                // 准备好主题集合
                List<Topic> topicList = topicDao.getTopicList();
                System.out.println("topicList ==> " + topicList.toString());
                session.setAttribute("topicList", topicList);
                session.setAttribute("addTopicMessage", "");
                //跳转到管理员页面
                response.sendRedirect(request.getContextPath() + "/views/admin/index.jsp");
            } else {
                session.setAttribute("addTopicMessage", "添加选项失败");
                request.getRequestDispatcher("/view/topic/add.jsp").forward(request, response);
            }
        } catch (Exception e) {
            session.setAttribute("addTopicMessage", "添加选项失败");
            request.getRequestDispatcher("/view/topic/add.jsp").forward(request, response);
        }

    }

    // 辅助方法：从Part中获取文件名
    private String getFileName(Part part) {
        for (String content : part.getHeader("content-disposition").split(";")) {
            if (content.trim().startsWith("filename")) {
                return content.substring(content.indexOf('=') + 1).trim().replace("\"", "");
            }
        }
        return null;
    }

    /**
     * 存储到本地并返回存储地址
     *
     * @param part
     * @param fileName
     * @param isCoverImage
     * @return
     * @throws IOException
     */
    private String saveFile(Part part, String fileName, boolean isCoverImage, HttpServletRequest request) throws IOException {
        InputStream fileContent = part.getInputStream();
        // 这里可以添加文件保存逻辑
        FileOutputStream out = null;
        fileName = fileName.split("\\.")[1];
        // 生成唯一文件名
        fileName = UUID.randomUUID().toString(true) + "." + fileName;
        if (isCoverImage) {
            out = new FileOutputStream(COVERIMAGE_IMAGE_SAVE_PATH + fileName);
            fileName = WEB_PATH + "coverimage/" + fileName;
        } else {
            out = new FileOutputStream(OPTION_IMAGE_SAVE_PATH + fileName);
            fileName = WEB_PATH + "option/" + fileName;
        }
        int length = 0;
        byte[] buffer = new byte[1024];
        while ((length = fileContent.read(buffer)) != -1) {
            out.write(buffer, 0, length);
        }
        out.close();
        fileContent.close();
        return fileName;
    }
}